<?php
namespace org;

use think\facade\Env;

class ImageDown  {
    /**
     * 下载图片
     * @param $url
     * @param string $flag
     * @return mixed
     */
    public static function down_load($url,$flag='vod')
    {
        if(substr($url,0,4)=='http'){
            return ImageDown::down_exec($url,$flag);
        }else{
            return $url;
        }
    }

    private static function down_exec($url,$flag='vod')
    {
        $upload_image_ext = 'jpg,png,gif';
        $ext = strrchr($url,'.');

        if(strpos($upload_image_ext,$ext)===false){
            $ext = '.jpg';
        }
        $file_name = md5($url) . $ext;

        // 上传附件路径
        $_upload_path = Env::get('root_path') . 'public/uploads' . '/' . $flag . '/';
        // 附件访问路径
        $_save_path = 'uploads'. '/' . $flag . '/' . $file_name;
        $filePath = $_upload_path . $file_name;

        $info = get_http_code($url);
        if (!empty($info)) {
            if ($info['http_code'] == 200) {
                if(file_exists($filePath) && filesize($filePath) == $info['download_content_length']){
                    return $_save_path;
                }else {
                    $img = mac_curl_get($url);
                    if ($img) {
                        $r = write_file($filePath,$img);
                        if(!$r){
                            return $url;
                        }
                        return $_save_path;
                    }else {
                       return $url;
                    }
                }
            }else {
                return $url;
            }
        }else {
            return $url;
        }

    }

}